#include "FifoBuffer.h"
#include <stdlib.h>
#include <string.h>


FifoBuffer::FifoBuffer(uint16_t   capacity) {
	m_bBuffer = new uint8_t[capacity];
	m_capacity = capacity;
	m_iPush = 0;
	m_iPop = 0;
}

FifoBuffer::~FifoBuffer() {

	delete[] m_bBuffer;
}

uint32_t FifoBuffer::Write(uint8_t* pbuf, uint32_t size) {
	uint32_t w_size = 0, free_size = 0;

	if ((size == 0) || (pbuf == NULL))
	{
		return 0;
	}

	free_size = FreeSize();
	if (free_size == 0)
	{
		return 0;
	}

	if (free_size < size)
	{
		size = free_size;
	}
	w_size = size;
	while (w_size-- > 0)
	{
		m_bBuffer[m_iPush++] = *pbuf++;
		if (m_iPush >= m_capacity)
		{
			m_iPush = 0;
		}
	}
	return size;
}

uint32_t FifoBuffer::Read(uint8_t* pbuf, uint32_t size)
{
	uint32_t r_size = 0, occupy_size = 0;

	if ((size == 0) || (pbuf == NULL))
	{
		return 0;
	}

	occupy_size = OccupySize();
	if (occupy_size == 0)
	{
		return 0;
	}

	if (occupy_size < size)
	{
		size = occupy_size;
	}
	r_size = size;
	while (r_size-- > 0)
	{
		*pbuf++ = m_bBuffer[m_iPop++];
		if (m_iPop >= m_capacity)
		{
			m_iPop = 0;
		}
		occupy_size--;
	}
	return size;
}


void FifoBuffer::Reset()
{
	m_iPush = 0;
	m_iPop = 0;
}


uint32_t FifoBuffer::TotalSize()
{

	return m_capacity;
}

uint32_t FifoBuffer::FreeSize()
{
	uint32_t size;
	size = m_capacity - OccupySize() - 1;
	return size;
}


uint32_t FifoBuffer::OccupySize()
{
	if (m_iPush == m_iPop) {
		return 0;
	}
	if (m_iPush > m_iPop) {
		return m_iPush - m_iPop;
	}
	else {
		return m_iPush + m_capacity - m_iPop;
	}
}